package com.solcoo.merchant.ui.login;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.android.common.util.ToastUtil;
import com.solcoo.merchant.Constant;
import com.solcoo.merchant.R;
import com.solcoo.merchant.base.BaseActivity;
import com.solcoo.merchant.base.task.TaskHelper;
import com.solcoo.merchant.base.task.TaskHelper.Callback;
import com.solcoo.merchant.base.task.TaskHelper.DefaultCallback;
import com.solcoo.merchant.manager.UserManager;
import com.solcoo.merchant.model.User;
import com.solcoo.merchant.ui.menu.MenuActivity;
import com.solcoo.merchant.ui.reg.GetCheckCodeActivity;
import com.solcoo.merchant.util.CheckUtil;
import com.solcoo.merchant.util.CheckUtil.CheckResult;

public class LoginActivity extends BaseActivity {

	private EditText name;

	private EditText pwd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (UserManager.getInstance().isLogin()) {
			Intent it = new Intent(this, MenuActivity.class);
			startActivity(it);
			return;
		}
		setContentView(R.layout.login);
		name = (EditText) findViewById(R.id.name);
		pwd = (EditText) findViewById(R.id.pwd);
		Button btn = (Button) findViewById(R.id.login);
		btn.setOnClickListener(loginOnClickListener);
	}

	private OnClickListener loginOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String nameValue = name.getText().toString();
			String pwdValue = pwd.getText().toString();
			CheckResult result = CheckUtil.checkLogin(nameValue, pwdValue);
			if (result.isSuccess()) {
				TaskHelper.oper(v.getContext(),
						Constant.URL.getLogin(nameValue, pwdValue),
						loginCallback, User.class);
			} else {
				ToastUtil.showToast(v.getContext(), result.failMsg);
			}
		}
	};

	private Callback<User> loginCallback = new DefaultCallback<User>(this) {

		private Dialog mDialog;

		@Override
		public void onSuccess(User result) {
			UserManager.getInstance().setUser(result);
			UserManager.getInstance().loginSuccess(mDialog, LoginActivity.this,
					"登录成功");
		}

	};

	public void regOnClick(View v) {
		Intent it = new Intent(v.getContext(), GetCheckCodeActivity.class);
		it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		v.getContext().startActivity(it);
	}

}
